var scripts = [null,'../assets/js/bootstrap-multiselect.js', "../assets/js/fuelux/fuelux.wizard.js", '../assets/js/bootstrap-tagsinput.js',
  "../assets/js/jquery.validate.js",
  null
]
var productId;
var $validation = false;
var isHasProduceId = false;
var focusIDs = [], lineIDs = [];
var $areaId = $("#areaId");
var $area2Id = $("#destinationId");
$('.page-content-area').ace_ajax('loadScripts', scripts, function () {
  jQuery(function ($) {
    $('[data-rel=tooltip]').tooltip();
    $('.input-file').ace_file_input({
      no_file: '请选择excel文件',
      btn_choose: '选择',
      btn_change: '更改',
      droppable: false,
      onchange: null,
      thumbnail: false//| true | large
    });

    $('#productRoutePackageBlack').tagsinput({});
    $('#productRoutePackageRed').tagsinput({});



    renderProductType('productType')
    renderActivityType('productActivityDiv')

    $('#fuelux-wizard-container')
      .ace_wizard({
        step: 1,//optional argument. wizard will jump to step "2" at first
      })
      .on('actionclicked.fu.wizard', function (e, info) {
        if (info.step == 1 && info.direction == 'next') {
          if($(".mainImg").attr("data-id")==""){
            alert("请添加主图")
            return false
          }
          if(!$utils.common.hasValue($area2Id.val())){
            alert("产品必须挂载到二级目的地，如果当前没有二级目的地，请到目的地管理添加")
            return false
          }


          if (!isHasProduceId) {
            addProduct()
          }
        }
        if (info.step == 3 && info.direction == 'next') {
          if (!isHasProduceId) {
            alert("没有产品ID")
            return false
          } else {
            addProductCostDescribe()
          }
        }
        if (info.step == 4 && info.direction == 'next') {
          if (!isHasProduceId) {
            alert("没有产品ID")
            return false
          } else {
            addProductLineFeature()
          }
        }
        if (info.step == 5 && info.direction == 'next') {
          if (!isHasProduceId) {
            alert("没有产品ID")
            return false
          } else {
            addProductReferTraffic()
          }
        }

        if (info.step == 6 && info.direction == 'next') {
          if (!isHasProduceId) {
            alert("没有产品ID")
            return false
          } else {
            addProductReferRoute()
          }
        }


        if (info.step == 7 && info.direction == 'next') {
          if (!isHasProduceId) {
            alert("没有产品ID")
            return false
          } else {
            addProductPrompt()
          }
        }


        if (info.step == 8 && info.direction == 'next') {
          if (!isHasProduceId) {
            alert("没有产品ID")
            return false
          } else {
            addProductUserInstructions()
          }
        }

      })
      .on('finished.fu.wizard', function (e) {
        if (!isHasProduceId) {
          alert("没有产品ID")
          return false
        } else {
          addProductImage()
        }
      });

    $('#modal-wizard-container').ace_wizard();
    $('#modal-wizard .wizard-actions .btn[data-dismiss=modal]').removeAttr('disabled');

    $(document).one('ajaxloadstart.page', function (e) {
      //in ajax mode, remove remaining elements before leaving page
    });
  })

  $("#webuploader-pick").click(function () {
    resourceModel(1, 1, 2, function (data) {
      console.log(data)
      $(".mainImg").attr("src", data[0].src);
      $(".mainImg").attr("data-id", data[0].id);
    })
  })


  /**新增产品基本信息*/


  $areaId.multiselect({
    enableFiltering: true,
    buttonClass: 'btn btn-white btn-primary',
    maxHeight: 200,
    numberDisplayed:1,
    templates: {
      button: '<button type="button" class="multiselect dropdown-toggle" data-toggle="dropdown"></button>',
      ul: '<ul class="multiselect-container dropdown-menu"></ul>',
      filter: '<li class="multiselect-item filter"><div class="input-group"><span class="input-group-addon"><i class="fa fa-search"></i></span><input class="form-control multiselect-search" type="text"></div></li>',
      filterClearBtn: '<span class="input-group-btn"><button class="btn btn-default btn-white btn-grey multiselect-clear-filter" type="button"><i class="fa fa-times-circle red2"></i></button></span>',
      li: '<li><a href="javascript:void(0);"><label></label></a></li>',
      divider: '<li class="multiselect-item divider"></li>',
      liGroup: '<li class="multiselect-item group"><label class="multiselect-group"></label></li>'
    },
    onChange: function (option, checked) {//change事件改变
      $area2Id.val("")
      $area2Id.multiselect("rebuild")
      if($utils.common.hasValue($areaId.val())){
        getChildrenNode($areaId.val().join(","))
      }
    },
  });
  $area2Id.multiselect({
    enableFiltering: true,
    buttonClass: 'btn btn-white btn-primary',
    maxHeight: 200,
    numberDisplayed:1,
    templates: {
      button: '<button type="button" class="multiselect dropdown-toggle" data-toggle="dropdown"></button>',
      ul: '<ul class="multiselect-container dropdown-menu"></ul>',
      filter: '<li class="multiselect-item filter"><div class="input-group"><span class="input-group-addon"><i class="fa fa-search"></i></span><input class="form-control multiselect-search" type="text"></div></li>',
      filterClearBtn: '<span class="input-group-btn"><button class="btn btn-default btn-white btn-grey multiselect-clear-filter" type="button"><i class="fa fa-times-circle red2"></i></button></span>',
      li: '<li><a href="javascript:void(0);"><label></label></a></li>',
      divider: '<li class="multiselect-item divider"></li>',
      liGroup: '<li class="multiselect-item group"><label class="multiselect-group"></label></li>'
    }
  });



  getChildrenNode(0)
  function getChildrenNode(id) {
    var params = {}
    params.pId = id;
    var url = $utils.ajax.setUrl("destination/getDestinationByPid");
    axios.post(url, params)
      .then(function (response) {
        renderChildrenNode(id, response.body)
      })
  }

  function renderChildrenNode(id, list) {
    var html = ``;
    if (list.length > 0) {
      $.each(list, function (key, val) {
        html += `<option value="${val.DESTINATION_ID}">${val.DESTINATION_NAME}</option>`
      })
    }
    if (id == 0) {
      $areaId.html(html)
      $areaId.multiselect("rebuild")
    } else {
      $area2Id.html(html)
      $area2Id.multiselect("rebuild")
    }
  }



  function addProduct() {
    var url = $utils.ajax.setUrl("product/addProduct");
    var params = {}
    params.productName = $("#productName").val()//产品名称
    params.productTitle = $("#productTitle").val()//酒店服务
    params.productTitle1 = $("#productTitle1").val()//景点接机
    params.productSubTitle = $("#productSubTitle").val()//副标题
    params.productType = $("#productType").val()
    params.productSelfVipFlag = $("#productSelfVipFlag").val()
    params.productPrice = $("#productPrice").val()

    //params.areaId=($("#areaId").val()||[]).join(",")
    params.destinationId = ($("#destinationId").val()||[]).join(",")
    params.productCode = $("#productCode").val()
    params.productFeatureSpot = $("#productFeatureSpot").val()
    //params.productRoutePackage = $("#productRoutePackage").html()  行程套餐改成两个字段
    params.productFeature = $("#productFeature").val()
    params.productServicePromise = $("#productServicePromise").val()
    params.productRoute = $("#productRoute").val()
    params.resourceId = $(".mainImg").attr("data-id") //产品主图

    var productRoutePackageBlack = $("#productRoutePackageBlack").tagsinput('items')
    var productRoutePackageRed = $("#productRoutePackageRed").tagsinput('items')
    params.productRoutePackageBlack = productRoutePackageBlack.join(",")
    params.productRoutePackageRed = productRoutePackageRed.join(",")

    var productTypeRefArr = []

    params.hotSort=$("#hotSort").val()||"1000"
    params.recommendSort=$("#recommendSort").val()||"1000"

    $("#productTypeRef input:checked").each(function (index, ele) {
      productTypeRefArr.push($(this).val())
    })
    if (productTypeRefArr.length > 0) {
      params.productTypeRef = productTypeRefArr.join(',')
    }
    var productActivyArr = []
    $("#productActivityDiv input:checked").each(function (index, ele) {
      productActivyArr.push($(this).val())
    })
    if (productActivyArr.length > 0) {
      params.productActivity = productActivyArr.join(',')
    }
    axios.post(url, params)
      .then(function (response) {
        productId = response.body
        isHasProduceId = true
        bootbox.alert("新增产品基本信息完成")
      })
  }

  /*导入价格*/

  $('#priceImport').click(function () {
    var path = $('#price-input-file').val();

    if (!$("#price-input-file")[0].files[0]) {
      bootbox.alert("请选择需要导入的excel文件!");
      return;
    }


    var formData = new FormData();
    formData.append("file", $("#price-input-file")[0].files[0]);
    formData.append("productId", productId);
    var urlUploadFile = $utils.ajax.setUrl("productPrice/uploadProductPrice");
    $.ajax({
      url: urlUploadFile,
      type: "post",
      async: true,
      cache: false,
      processData: false,
      contentType: false,
      data: formData,
      success: function (data) {
        var result = JSON.parse(data)
        if (result.code == "10000") {
          bootbox.alert("价格上传成功")
          renderPriceList(result.body)
        } else {
          bootbox.alert(result.msg)
        }
      }
    });
  })

  function renderPriceList(list) {
    var html = ''
    $.each(list, function (key, val) {
      html += `<tr><td class="hidden-480"><input class="priceDate" type="text" value="${val.priceDate}"></td>
                        <td class="hidden-480"><input class="backDate" type="text" value="${val.backDate}"></td>
                        <td class="hidden-480"><input class="productPrice" type="text" value="${val.productPrice!=null?val.productPrice:""}"></td>
                        <td class="hidden-480"><input class="childrenPrice" type="text" value="${val.childrenPrice!=null?val.childrenPrice:""}"></td>
                        <td class="hidden-480"><input class="productRemainNumDay" type="text" value="${val.productRemainNumDay!=null?val.productRemainNumDay:""}"></td>
                        <td class="hidden-480"><input type="text" value="${val.priceDetail}"></td>
                        <td class="hidden-480"><span class="btn btn-sm btn-warning" onclick="updateProductPriceDayById(this,${val.priceId})">修改</span>
                        <span class="btn btn-sm btn-warning" onclick="deleteProductPriceDayById(this,${val.priceId})">删除</span></td></tr>`

    })

    $(".priceTable tbody").html(html)
  }

  /**新增产品费用说明*/
  function addProductCostDescribe() {
    var url = $utils.ajax.setUrl("productCostDescribe/addOrUpdateProductCostDescribe");
    var params = {}
    params.productId = productId;
    params.list = []
    var productCostDescribes = []
    $('.CostDescribe textarea').each(function (index, ele) {
      productCostDescribes.push({
        "describeTypeName": $(ele).attr("data-title"),
        "describeIsContain": $(ele).attr("describeIsContain"),
        "describeSort": index,
        "describeTypeDetail": $(ele).val()
      })
    })
    params.list = productCostDescribes
    axios.post(url, params)
      .then(function (response) {
        bootbox.alert("新增产品费用说明成功")
      })
  }

  /**新增产品线路特色*/
  function addProductLineFeature() {
    var url = $utils.ajax.setUrl("productLineFeature/addOrUpdateProductLineFeature");
    var params = {}
    params.productId = productId
    var productLineFeatures = []
    $('.lineFeature textarea').each(function (index, ele) {
      productLineFeatures.push({
        "featureTypeName": $(ele).attr("data-title"),
        "featureSort": $(ele).attr("featureSort"),
        "featureTypeDetail": $(ele).val()
      })
    })
    params.list = productLineFeatures
    axios.post(url, params)
      .then(function (response) {
        bootbox.alert("新增产品线路特色完成")
      })
  }


  /**新增产品参考交通*/
  function addProductReferTraffic() {
    var url = $utils.ajax.setUrl("productReferTraffic/addOrUpdateProductReferTraffic");
    var params = {}
    params.productId = productId;

    var productReferTraffics = []
    productReferTraffics.push({
      "goBackType": 1,
      "startStation": $("#startStation1").val(),
      "endStation": $("#endStation1").val(),
      "startDay": "",
      "endDay": "",
      "startTime": "",
      "endTime": "",
      "trafficSumTime": $("#trafficSumTime1").val(),
      "trafficDetail": $("#trafficDetail1").val()
    })
    productReferTraffics.push({
      "goBackType": 2,
      "startStation": $("#startStation2").val(),
      "endStation": $("#endStation2").val(),
      "startDay": "",
      "endDay": "",
      "startTime": "",
      "endTime": "",
      "trafficSumTime": $("#trafficSumTime2").val(),
      "trafficDetail": $("#trafficDetail2").val()
    })
    params.list = productReferTraffics
    axios.post(url, params)
      .then(function (response) {
        bootbox.alert("新增产品参考交通完成")
      })
  }


  /*温馨提示*/
  function addProductPrompt() {

    var url = $utils.ajax.setUrl("product/addOrUpdateProductPrompt");
    var params = {}
    params.productId = productId
    params.productPrompt= $('#productPrompt').val()
    axios.post(url, params)
      .then(function (response) {
        bootbox.alert(response.msg)
      })
  }


  /*温馨提示*/
  function addProductUserInstructions() {
    var url = $utils.ajax.setUrl("product/addOrUpdateProductUserInstructions");
    var params = {}
    params.productId = productId
    params.productUserInstructions= $('#UserInstructions').val()
    axios.post(url, params)
      .then(function (response) {
        bootbox.alert(response.msg)
      })
  }

  /*增加天数*/
  var days = 1;
  $('#addOneDay').click(function () {
    var $clone = $(".Trip .day[data-day=" + days + "]").clone(true);
    var $wrapper = $('<div class="wrapper"></div>')
    $wrapper.html($clone)
    days++;
    $wrapper.find(".d").html(days)
    $wrapper.find(".day").attr("data-day", days)
    $('.Trip .days').append($wrapper.html())
  })

  $('#subtractTastDay').click(function () {
    var day = $('.Trip .days>div.day:last').attr("data-day")
    if (day == 1) {
      bootbox.alert("第一天不能删除")
    } else {
      $('.Trip .days>div.day:last').remove()
      days--;
    }
  })

  /**新增产品参考行程*/
  function addProductReferRoute() {
    var url = $utils.ajax.setUrl("productReferRoute/addOrUpdateProductReferRoute");
    var params = {}
    params.productId = productId;
    params.list = []

    $('.Trip .day').each(function (index, ele) {
      var item = {}
      item.stageIdSort = $(this).attr("data-day")
      item.stageName = $(this).find("input[data=11]").val() + '--' + $(this).find("input[data=12]").val()
      item.productReferRouteDetails = [{}, {}, {}, {}, {}]
      item.productReferRouteDetails[0].referSort = 1
      item.productReferRouteDetails[0].detailTypeName = '集合时间'
      item.productReferRouteDetails[0].detailTypeDetail = '集合时间:' + "" + '******' +
        '集合地点:' + "";


      item.productReferRouteDetails[1].referSort = 2
      item.productReferRouteDetails[1].detailTypeName = '甄选美食'
      item.productReferRouteDetails[1].detailTypeDetail = '早餐:' + $(this).find("input[data=13]").val() + '******' +
        '午餐:' + $(this).find("input[data=14]").val() + '******' +
        '晚餐:' + $(this).find("input[data=15]").val();


      item.productReferRouteDetails[2].referSort = 3
      item.productReferRouteDetails[2].detailTypeName = '酒店住宿'
      item.productReferRouteDetails[2].detailTypeDetail =$(this).find("input[data=17]").val();

      item.productReferRouteDetails[3].referSort = 4
      item.productReferRouteDetails[3].detailTypeName = '游览景点'
      item.productReferRouteDetails[3].detailTypeDetail = $(this).find("textarea[data=31]").val();


      item.productReferRouteDetails[4].referSort = 5
      item.productReferRouteDetails[4].detailTypeName = '行程介绍'
      item.productReferRouteDetails[4].detailTypeDetail = $(this).find("textarea[data=32]").val();

      params.list.push(item)
    })
    axios.post(url, params).then(function (response) {
      bootbox.alert("新增产品参考行程完成")
    })
  }

  /**产品焦点图*/

  $("#webuploader-pick-focus").click(function () {
    resourceModel(2, 1, 2, function (data) {

      $.each(data, function (key, val) {
        if ($.inArray(val.id, focusIDs) == -1) {
          focusIDs.push(val.id);
          var html = '<li class="item">' +
            ' <div class="thumb">' +
            '<img  data-id="' + val.id + '"' + 'src="' + val.src + '">' +
            '<span onclick="delProductImg(this,1)" class="btn btn-sm btn-white"> <icon class="ace-icon glyphicon glyphicon-remove red"></icon>删除</span>' +
            '</div>' +
            '</li>'
          $(".productImgs .imgslist-focus").append(html)
        }
      })
    })
  })

  /**产品旅行图*/
  $("#webuploader-pick-line").click(function () {
    resourceModel(2, 1, 2, function (data) {
      $.each(data, function (key, val) {
        if ($.inArray(val.id, lineIDs) == -1) {
          lineIDs.push(val.id);
          var html = '<li class="item">' +
            ' <div class="thumb">' +
            '<img  data-id="' + val.id + '"' + 'src="' + val.src + '">' +
            '<span onclick="delProductImg(this,2)" class="btn btn-sm btn-white"> <icon class="ace-icon glyphicon glyphicon-remove red"></icon>删除</span>' +
            '</div>' +
            '</li>'
          $(".productImgs .imgslist-line").append(html)
        }
      })
    })
  })


  /**新增产品图片*/
  function addProductImage() {
    var url = $utils.ajax.setUrl("product/addProductImage");
    var params = {}
    params.productId = productId;
    if (focusIDs.length > 0) {
      params.resourceProductIds = focusIDs.join(",")
    } else {
      params.resourceProductIds = ""
    }
    if (lineIDs.length > 0) {
      params.resourceProductLineFeatureIds = lineIDs.join(",")
    } else {
      params.resourceProductLineFeatureIds = ""
    }

    axios.post(url, params)
      .then(function (response) {
        bootbox.alert("添加产品完成")
        window.location.href = "#page/product/list"
      })
  }


});

function delProductImg(obj, type) {
  $(obj).parents(".item").remove()
  if (type == 1) {
    removeArrItem(focusIDs, $(obj).prev("img").attr("data-id"))
  }
  if (type == 2) {
    removeArrItem(lineIDs, $(obj).prev("img").attr("data-id"))
  }
}


function removeItem(obj) {
  $(obj).parents(".form-group").remove()
}
$("#addFinerCost").click(function () {
  modelAddFinerCost(function (data) {
    var html = `<div class="space-2"></div><div class="form-group">
                <label class="control-label col-xs-12 col-sm-3 no-padding-right">【${data.t1}】 <i class="ace-icon glyphicon glyphicon-remove red2 cursor-p" onclick="removeItem(this)"></i></label>
                <div class="col-xs-12 col-sm-9">
                  <div class="clearfix">
                    <textarea class="col-sm-12" data-title="${data.t1}" describeIsContain="${data.t2}" ></textarea>
                  </div>
                </div>
              </div>`

    if(data.t2==1){
      $("#IsContain").append(html)
    }else{
      $("#NotContain").append(html)
    }
  })
})

function updateProductPriceDayById(obj,priceId) {
  bootbox.confirm("确认修改吗", function (v) {
    if (v) {
      var url = $utils.ajax.setUrl("productPrice/updateProductPriceDayById");
      var params = {}
      params.productId = $utils.string.getQueryParam("id")
      params.priceId = priceId;
      params.priceDate = $(obj).parents('tr').find(".priceDate").html()
      params.backDate = $(obj).parents('tr').find(".backDate").html()
      params.productPrice = $(obj).parents('tr').find(".productPrice").val();
      params.childrenPrice = $(obj).parents('tr').find(".childrenPrice").val();
      params.productRemainNumDay = $(obj).parents('tr').find(".productRemainNumDay").val();
      params.priceDetail = $(obj).parents('tr').find(".priceDetail").val();
      axios.post(url, params)
        .then(function (response) {
          bootbox.alert(response.msg)
        })
    }
  })
}
function deleteProductPriceDayById(obj,priceId) {
  bootbox.confirm("确认删除吗", function (v) {
    if (v) {
      var url = $utils.ajax.setUrl("productPrice/deleteProductPriceDayById");
      var params = {}
      params.productId = productId;
      params.priceId = priceId;
      axios.post(url, params)
        .then(function (response) {
          bootbox.alert(response.msg)
          if (response.code == '10000') {
            $(obj).parents("tr").remove()
          }
        })
    }
  })
}
